<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head th:replace="fragments/head :: head"></head>

<body>
<!-- Wrapper -->
<div id="wrapper">
    <div id="sidebar-wrapper" th:replace="fragments/nav :: nav"></div>
    <div id="bootstrap-data" th:attr="data-bootstrap=${data}"></div>
    <div id="bootstrap-html" th:attr="data-html=${tableHtml}"></div>
    <div id="page-content-wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-12">
                    <input id="jobId" th:hidden="true"/>
                    <h1 style="margin-bottom: 15px" th:text="${title}"></h1>
                    <div th:if="${error != null}"
                         th:text="${error}"
                         class="alert alert-danger"
                         role="alert">
                    </div>
                    <div th:if="${error == null}">
                        <div class="form-group">
                            <label class="control-label" for="timeseriesNames">Timeseries List:</label><br/>
                            <select id="timeseriesNames" class="form-control" multiple="multiple"
                                    th:field="*{timeseries}" th:required="true">
                                <option th:each="timeseries : ${timeseriesNames}"
                                        th:value="${timeseries.getLeft()}"
                                        th:selected="true"
                                        th:text="${timeseries.getRight()}"></option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="control-label" for="saveAsJob">Save as a scheduled Job:</label><br/>
                            <div class="btn-toolbar">
                                <button type="button" class="btn btn-success" id="saveAsJob" name="saveAsJob" data-toggle="modal" data-target="#saveConfirmModal">Create Job</button>
                            </div>
                        </div>
                        <div class="row" id="chart-container"></div>
                        <div class="form-group" id="table-container"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- save confirmation -->
    <div id="saveConfirmModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-body">
                    <p id="saveConfirmModalCode">Save the job finally?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn btn-primary" id="saveConfirmModalYes">Yes
                    </button>
                    <button type="button" data-dismiss="modal" class="btn" id="saveConfirmModalNo">No</button>
                </div>
            </div>
        </div>
    </div>
    <!-- cron confirmation -->
    <div id="cronConfirmModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-body">
                    <p id="cronConfirmModalCode">Ready to launch the job (YES action won't launch, it just redirects to job launching page)?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn btn-primary" id="cronConfirmModalYes">Yes
                    </button>
                    <button type="button" data-dismiss="modal" class="btn" id="cronConfirmModalNo">No</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script language="javascript" type="text/javascript" th:inline="javascript">
    /*<![CDATA[*/
    function getIndex(d) {
        if (d.classed) {
            return Number(d.classed.split('-')[1]);
        }
        return d[0].series;
    }

    function displayGraph(data) {
        if (!data) {
            return;
        }
        $('svg').remove();
        $('#chart-container')[0].innerHTML += '<svg></svg>';
        $('svg').height(650);
        nv.addGraph(function () {
            var chart = nv.models.lineWithFocusChart()
                .margin({left: 100, right: 100})
                .height(600)
                .useInteractiveGuideline(true)
                .showLegend(false);
            const timeFormat = d3.time.format.utc("%a %b %d, %H:%M");
            chart.xAxis
                .axisLabel('Time')
                .tickFormat(function (x) {
                    const currentDate = new Date(x * 1000);
                    return timeFormat(currentDate);
                });
            chart.yAxis
                .axisLabel('Metric')
                .tickFormat(d3.format('.3s'));
            chart.x2Axis
                .axisLabel('Time')
                .tickFormat(function (x) {
                    const currentDate = new Date(x * 1000);
                    return timeFormat(currentDate);
                });
            chart.y2Axis
                .axisLabel('Metric')
                .tickFormat(d3.format('.3s'));
            d3.select('svg')
                .datum(data)
                .call(chart);
            // The index of the first anomaly series
            const anomalyStart = (data.length * 2) / 3;

            function updateAnomalies() {
                d3.select('.nv-groups')
                    .selectAll('.nv-group')
                    .each(function (d) {
                        // Hide the lines for anomalies
                        if (getIndex(d) >= anomalyStart) {
                            d3.select(this)
                                .selectAll('path')
                                .style('stroke-opacity', 0);
                        }
                    });
                d3.select('.nv-focusWrap')
                    .select('.nv-groups')
                    .selectAll('.nv-group')
                    .each(function (d) {
                        if (getIndex(d) >= anomalyStart) {
                            d3.select(this)
                                .selectAll('path')
                                .style('stroke-opacity', 0);
                        }
                    });
                d3.select('.nv-scatterWrap')
                    .select('.nv-groups')
                    .selectAll('.nv-group')
                    .each(function (d) {
                        if (getIndex(d) < anomalyStart) {
                            return;
                        }
                        d3.select(this)
                            .selectAll('path')
                            .each(function (b) {
                                // Highlight anomaly points as red except
                                // if the point is null
                                if (!b[0].y) {
                                    d3.select(this)
                                        .style('stroke-opacity', 0)
                                        .style('fill-opacity', 0)
                                        .style('stroke-width', 0);
                                    return;
                                }
                                d3.select(this)
                                    .style('fill', 'red')
                                    .style('stroke', 'red')
                                    .style('stroke-opacity', 0.8)
                                    .style('fill-opacity', 0.6)
                                    .style('stroke-width', 5);
                            })
                    });
                // Hook onto the brush event so that the anomalies update while
                // changing the focus
                const prevBrush = chart.focus.dispatch.on('onBrush');

                function hookBrush(e) {
                    prevBrush(e);
                    updateAnomalies();
                }

                // Rehook only if the line chart has redefined the event handler
                if (prevBrush.name !== 'hookBrush') {
                    chart.focus.dispatch.on('onBrush', hookBrush);
                }
            }

            // Hook onto all update events to make sure the
            // anomalies are displayed correctly
            updateAnomalies();
            chart.dispatch.on('renderEnd', updateAnomalies);
            chart.dispatch.on('stateChange', updateAnomalies);
            chart.dispatch.on('changeState', updateAnomalies);
            nv.utils.windowResize(function () {
                chart.update();
                updateAnomalies();
            });
            return chart;
        });
    }

    $(document).ready(function () {
        $('#timeseriesNames').multiselect({
            maxHeight: 400,
            nonSelectedText: 'Select Timeseries',
            includeSelectAllOption: true,
            enableFiltering: true,
            onSelectAll: function() {
                displayGraph($('#bootstrap-data').data('bootstrap'));
            },
            onChange: function(option, checked, select) {
                var graphData = $('#bootstrap-data').data('bootstrap');
                var selected = $('#timeseriesNames').val();
                var result = [];
                var i;
                if (selected.length > 0) {
                    result = new Array(selected.length * 3);
                    for(i = 0; i < selected.length; i = i + 1) {
                        result[i * 2] = graphData[selected[i] * 2];
                        result[i * 2 + 1] = graphData[selected[i] * 2 + 1];
                    }
                    for(i = 0; i < selected.length; i = i + 1) {
                        var x = selected.length * 2 + i;
                        var y = (graphData.length * 2) / 3 + parseInt(selected[i]);
                        result[x] = graphData[y];
                    }
                    for(i = 0; i < result.length; i = i + 1) {
                        result[i].classed = "series-" + i;
                    }
                }
                displayGraph(result);
            }
        });
        const tableHtml = $('#bootstrap-html').attr('data-html');
        $('#table-container').html(tableHtml);
        $('#reportTable').DataTable({
            "pageLength": 100,
            "order": [[ 3, "desc" ]]
        });
        displayGraph($('#bootstrap-data').data('bootstrap'));
    });

    $("#saveConfirmModalYes").click(function () {
        var data = {};
        var d = new Date();
        data.query = [[${userQuery.getQuery()}]];
        data.granularity = [[${userQuery.getGranularity()}]];
        data.granularityRange = [[${userQuery.getGranularityRange()}]];
        data.timeseriesRange = [[${userQuery.getTimeseriesRange()}]];
        data.sigmaThreshold = [[${userQuery.getSigmaThreshold()}]];
        data.clusterId = [[${userQuery.getClusterId()}]];
        data.hoursOfLag = [[${userQuery.getHoursOfLag()}]];
        data.tsFramework = [[${userQuery.getTsFramework()}]];
        data.tsModels = [[${userQuery.getTsModels()}]];
        data.adModels = [[${userQuery.getAdModels()}]];
        data.growthModel = [[${userQuery.getGrowthModel()}]];
        data.yearlySeasonality = [[${userQuery.getYearlySeasonality()}]];
        data.weeklySeasonality = [[${userQuery.getWeeklySeasonality()}]];
        data.dailySeasonality = [[${userQuery.getDailySeasonality()}]];
        data.testName = "Job_" + d.toLocaleDateString() + "_" + d.toLocaleTimeString();
        data.testDescription = "";
        data.owner = "";
        data.ownerEmail = "";
        data.emailOnNoData = "false";
        data.queryUrl = "";
        data.frequency = [[${userQuery.getGranularity()}]];
        $.ajax({
            type: 'POST',
            url: '/SaveJobInfo',
            data: JSON.stringify(data),
            contentType: "application/json",
            dataType: 'text',
            success: function (response) {
                if ($.isEmptyObject(response)) {
                    // Else there was a warning, but not a failure
                    showWarningMessage("Something went wrong! Try again.");
                } else {
                    showInfoMessage("Job saved successfully.");
                    setTimeout(function () {
                        $('#jobId').val(response);
                        $('#cronConfirmModalCode').html();
                        $('#cronConfirmModal').modal('show');
                    }, 1000);
                }
            },
            error: ajaxMessage
        });
    });

    $("#cronConfirmModalYes").click(function () {
        setTimeout(function () {
            window.location.href = '/Jobs/' + $('#jobId').val();
        }, 700);
    });

    $("#cronConfirmModalNo").click(function () {
        setTimeout(function () {
            window.location.href = '/Jobs/' + $('#jobId').val();
        }, 700);
    });

    $("#saveConfirmModalNo").click(function () {
        showWarningMessage("Job is not saved.");
    });

    /*]]>*/
</script>

</body>

</html>
